document.addEventListener('DOMContentLoaded', function() {
  // Check if user is authenticated
  if (ApiService.redirectIfNotAuthenticated()) {
    return;
  }
  
  // Initialize components
  const topNavBar = new TopNavBar();
  topNavBar.init();
  
  const sideBar = new SideBar();
  sideBar.init('transactions');
  
  // Get transaction ID from URL parameter
  const urlParams = new URLSearchParams(window.location.search);
  const transactionId = urlParams.get('id');
  
  if (!transactionId) {
    showError('交易ID不能为空');
    return;
  }
  
  // Load transaction details
  loadTransactionDetail(transactionId);
  
  /**
   * Load transaction details
   */
  function loadTransactionDetail(id) {
    ApiService.get(`/api/transaction/${id}`)
      .then(response => {
        if (response.code === 0 && response.data) {
          renderTransactionDetail(response.data);
        } else {
          showError(response.message || '获取交易详情失败');
        }
      })
      .catch(error => {
        console.error('Error loading transaction detail:', error);
        showError('获取交易详情失败');
      });
  }
  
  /**
   * Render transaction detail
   */
  function renderTransactionDetail(transaction) {
    const containerElement = document.getElementById('transaction-detail-content');
    
    // Determine if income or expense
    const isIncome = [1, 5].includes(transaction.tradeType); // 充值或退款为收入
    
    // Get status class
    const statusClass = getStatusClass(transaction.status);
    const statusText = getStatusText(transaction.status);
    const statusDesc = getStatusDescription(transaction);
    
    // Format amount with sign
    const amountClass = isIncome ? 'income' : 'expense';
    const amountPrefix = isIncome ? '+' : '-';
    const formattedAmount = `${amountPrefix}¥${Math.abs(transaction.amount).toFixed(2)}`;
    
    // Build HTML
    let html = `
      <div class="transaction-status-banner ${statusClass}">
        <div class="transaction-status-icon">
          <i class="fas ${getStatusIcon(transaction.status)}"></i>
        </div>
        <div class="transaction-status-info">
          <div class="transaction-status-title">${statusText}</div>
          <div class="transaction-status-desc">${statusDesc}</div>
        </div>
      </div>
      
      <div class="transaction-amount-section">
        <div class="transaction-amount-label">${getTransactionTypeLabel(transaction.tradeType)}</div>
        <div class="transaction-amount ${amountClass}">${formattedAmount}</div>
      </div>
      
      <div class="card">
        <div class="card-body">
          <div class="transaction-detail-section">
            <div class="transaction-detail-title">交易信息</div>
            <div class="detail-item">
              <div class="detail-label">交易类型</div>
              <div class="detail-value">${transaction.tradeTypeName || getTransactionTypeName(transaction.tradeType)}</div>
            </div>
            <div class="detail-item">
              <div class="detail-label">交易流水号</div>
              <div class="detail-value">${transaction.tradeNo}</div>
            </div>
            <div class="detail-item">
              <div class="detail-label">交易时间</div>
              <div class="detail-value">${Utils.formatDate(transaction.createTime, true)}</div>
            </div>
            <div class="detail-item">
              <div class="detail-label">交易状态</div>
              <div class="detail-value">${statusText}</div>
            </div>
            ${transaction.updateTime ? `
              <div class="detail-item">
                <div class="detail-label">更新时间</div>
                <div class="detail-value">${Utils.formatDate(transaction.updateTime, true)}</div>
              </div>
            ` : ''}
            <div class="detail-item">
              <div class="detail-label">交易后余额</div>
              <div class="detail-value">¥${transaction.balance.toFixed(2)}</div>
            </div>
          </div>
          
          ${transaction.tradeType === 3 ? `
            <div class="transaction-detail-section">
              <div class="transaction-detail-title">转账信息</div>
              <div class="detail-item">
                <div class="detail-label">收款方</div>
                <div class="detail-value">${transaction.targetAccount}</div>
              </div>
            </div>
          ` : ''}
          
          ${transaction.tradeType === 1 || transaction.tradeType === 2 ? `
            <div class="transaction-detail-section">
              <div class="transaction-detail-title">支付信息</div>
              <div class="detail-item">
                <div class="detail-label">支付渠道</div>
                <div class="detail-value">${transaction.channelName || getChannelName(transaction.channel)}</div>
              </div>
            </div>
          ` : ''}
          
          ${transaction.remark ? `
            <div class="transaction-detail-section">
              <div class="transaction-detail-title">备注</div>
              <div class="detail-item">
                <div class="detail-value">${transaction.remark}</div>
              </div>
            </div>
          ` : ''}
        </div>
      </div>
      
      <div class="transaction-actions">
        <button class="btn btn-outline" onclick="window.history.back()">
          <i class="fas fa-arrow-left"></i> 返回列表
        </button>
        <button class="btn btn-outline" id="share-btn">
          <i class="fas fa-share-alt"></i> 分享
        </button>
      </div>
    `;
    
    containerElement.innerHTML = html;
    
    // Add share functionality
    document.getElementById('share-btn').addEventListener('click', function() {
      showShareDialog(transaction);
    });
  }
  
  /**
   * Show error message
   */
  function showError(message) {
    const containerElement = document.getElementById('transaction-detail-content');
    
    containerElement.innerHTML = `
      <div class="error-state">
        <i class="fas fa-exclamation-circle"></i>
        <p>${message}</p>
        <button class="btn btn-outline" onclick="window.history.back()">
          <i class="fas fa-arrow-left"></i> 返回
        </button>
      </div>
    `;
  }
  
  /**
   * Show share dialog
   */
  function showShareDialog(transaction) {
    // Create a temporary input element to copy the link
    const tempInput = document.createElement('input');
    tempInput.value = window.location.href;
    document.body.appendChild(tempInput);
    tempInput.select();
    document.execCommand('copy');
    document.body.removeChild(tempInput);
    
    Toast.success('链接已复制到剪贴板');
  }
  
  /**
   * Get status class for styling
   */
  function getStatusClass(status) {
    switch (status) {
      case 1: return 'success';
      case 0: return 'processing';
      case 2: return 'failed';
      default: return 'processing';
    }
  }
  
  /**
   * Get status text
   */
  function getStatusText(status) {
    switch (status) {
      case 1: return '交易成功';
      case 0: return '处理中';
      case 2: return '交易失败';
      default: return '未知状态';
    }
  }
  
  /**
   * Get status icon
   */
  function getStatusIcon(status) {
    switch (status) {
      case 1: return 'fa-check';
      case 0: return 'fa-spinner fa-spin';
      case 2: return 'fa-times';
      default: return 'fa-question';
    }
  }
  
  /**
   * Get status description
   */
  function getStatusDescription(transaction) {
    switch (transaction.status) {
      case 1:
        return `您的交易已成功完成，交易号 ${transaction.tradeNo}`;
      case 0:
        return '您的交易正在处理中，请稍后刷新查看最新状态';
      case 2:
        return '很抱歉，您的交易失败，请稍后重试或联系客服';
      default:
        return '';
    }
  }
  
  /**
   * Get transaction type label
   */
  function getTransactionTypeLabel(type) {
    switch (type) {
      case 1: return '充值金额';
      case 2: return '提现金额';
      case 3: return '转账金额';
      case 4: return '支付金额';
      case 5: return '退款金额';
      default: return '交易金额';
    }
  }
  
  /**
   * Get transaction type name
   */
  function getTransactionTypeName(type) {
    switch (type) {
      case 1: return '充值';
      case 2: return '提现';
      case 3: return '转账';
      case 4: return '支付';
      case 5: return '退款';
      default: return '未知类型';
    }
  }
  
  /**
   * Get channel name
   */
  function getChannelName(channel) {
    switch (channel) {
      case 'ALIPAY': return '支付宝';
      case 'WECHAT': return '微信支付';
      case 'BANK_CARD': return '银行卡';
      case 'INTERNAL': return '内部账户';
      default: return channel;
    }
  }
});
